﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.CUiFLEXCableNewEditorWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.Flexibles;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui.WPF;


namespace DnProcessSimulateCommands;

public class CUiFLEXCableNewEditorWindow : 
  TxWindow,
  ICApFLEXCableEditorSelection,
  IComponentConnector
{
  private CApCableFrameAttachmentRetriever m_frameAttachmentRetriever = new CApCableFrameAttachmentRetriever();
  private readonly List<IDisposable> m_disposableObjects;
  private readonly ICApFLEXSimulationPlayer m_simulationPlayer;
  private bool m_isWindowLoading = true;
  public bool m_comboChanged;
  internal CUiFLEXCableNewEditorWindow dMainDialog;
  internal Grid CableCreationChoiceGrid;
  internal TextBlock labelCableCreationMode;
  internal System.Windows.Controls.ComboBox CableCreationModeCombo;
  internal CApCableBasicRequiredParametersControl BasicRequiredParametersControl;
  internal CApCableBasicRequiredPointCloudParametersControl BasicRequiredPointCloudParametersControl;
  internal Expander ExpanderParameters;
  internal CApCableParametersNewUserControl ParametersUserControl;
  internal CApCableParametersPointCloudUserControl ParametersPointCloudUserControl;
  internal Expander ExpanderAttachments;
  internal CApCableAttachmentsNewUserControl AttachmentsUserControl;
  internal System.Windows.Controls.Button btnGenerate;
  internal System.Windows.Controls.Button btnClose;
  internal Image iMessageType;
  internal TextBlock tbMessage;
  private bool _contentLoaded;

  [DllImport("user32.dll")]
  private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

  [DllImport("user32.dll")]
  private static extern int EnableMenuItem(IntPtr hMenu, uint wIDEnableItem, uint wEnable);

  public CApFlexParameterController ParameterController { get; set; }

  public CApFLEXCableNewAttributeViewModel AttributeViewModel { get; set; }

  private CApCableStatusMessageFactory CableStatusMessageFactory { get; set; }

  private bool IsEditMode => this.AttributeViewModel.IsEditMode;

  public ITxCable Cable
  {
    get => this.AttributeViewModel.Cable;
    set => this.AttributeViewModel.Cable = value;
  }

  public ITxObject ParentEquipment
  {
    get => this.AttributeViewModel.CableScopeStatus.ParentEquipment;
    set => this.AttributeViewModel.CableScopeStatus.ParentEquipment = value;
  }

  private bool IsComboLoading { get; set; }

  public CApFlexCableController CableController { get; set; }

  public CUiFLEXCableNewEditorWindow(CUiFLEXCreateCableCmd command)
    : this(command, (ITxCable) null, (ITxPointCloudLayer) null, (ITxComponent) null, true)
  {
  }

  public CUiFLEXCableNewEditorWindow(CUiFLEXCreateCableCmd command, ITxComponent equipmentScope)
    : this(command, (ITxCable) null, (ITxPointCloudLayer) null, equipmentScope, true)
  {
  }

  public CUiFLEXCableNewEditorWindow(
    CUiFLEXCreateCableCmd command,
    ITxCable cable,
    bool isLicenseOn)
    : this(command, cable, (ITxPointCloudLayer) null, (ITxComponent) null, isLicenseOn)
  {
  }

  public CUiFLEXCableNewEditorWindow(
    CUiFLEXCreateCableCmd command,
    ITxPointCloudLayer pointCloudLayer,
    bool isLicenseOn)
    : this(command, (ITxCable) null, pointCloudLayer, (ITxComponent) null, isLicenseOn)
  {
  }

  private CUiFLEXCableNewEditorWindow(
    CUiFLEXCreateCableCmd command,
    ITxCable cable,
    ITxPointCloudLayer pointCloudLayer,
    ITxComponent equipmentScope,
    bool isLicenseOn)
  {
    this.m_disposableObjects = new List<IDisposable>();
    this.m_simulationPlayer = (ICApFLEXSimulationPlayer) new CApFLEXSimulationPlayer(TxApplication.ActiveDocument.SimulationPlayer);
    this.CreateParameterController(command);
    this.CreateDialog(cable, pointCloudLayer, equipmentScope, isLicenseOn);
  }

  private void TxWindow_Loaded(object sender, RoutedEventArgs e)
  {
    this.m_isWindowLoading = false;
    ((UIElement) this).Refresh();
    this.RegisterActiveDocumentEvents();
    this.InitCableParameters();
    this.InitializeUpdaters();
    this.EndOfLoadingControl();
  }

  private void TxWindow_Closed(object sender, CancelEventArgs e)
  {
    this.CloseDialog();
    this.UnregisterUserControlEvent();
    this.UnregisterActiveDocumentEvents();
  }

  private void CloseDialog()
  {
    this.ClearDisposableObjects();
    this.DidCloseUserControl();
  }

  private void DidCloseUserControl()
  {
    this.AttachmentsUserControl.DidDialogClose();
    this.ParametersUserControl.DidDialogClose();
    this.BasicRequiredParametersControl.DidDialogClose();
    this.BasicRequiredPointCloudParametersControl.DidDialogClose();
    this.ParametersPointCloudUserControl.DidDialogClose();
    if (this.AttachmentsUserControl.NewAttachmentWindow == null)
      return;
    ((Window) this.AttachmentsUserControl.NewAttachmentWindow).Close();
    this.AttachmentsUserControl.NewAttachmentWindow = (CUiFLEXAttachmentEditorWindow) null;
  }

  private void ClearDisposableObjects()
  {
    foreach (IDisposable disposableObject in this.m_disposableObjects)
      disposableObject.Dispose();
    this.m_disposableObjects.Clear();
  }

  private void CreateDialog(
    ITxCable cable,
    ITxPointCloudLayer pointCloudLayer,
    ITxComponent parentEquipment,
    bool isLicenseOn)
  {
    this.InitializeComponent();
    this.AttributeViewModel = new CApFLEXCableNewAttributeViewModel()
    {
      IsLicenseOn = isLicenseOn,
      OptimizationPointCloudLayer = pointCloudLayer
    };
    this.InitCableScopeStatus(cable, parentEquipment);
    this.InitDialog(pointCloudLayer == null ? CUiFLEXCreationMode.MANUAL : CUiFLEXCreationMode.FROM_POINT_CLOUD);
    this.CableController = new CApFlexCableController(this.ParameterController, (ICApFLEXCableAttributeViewModel) this.AttributeViewModel);
    if (this.Cable == null)
      return;
    this.CableController.InitViewModelWithCable(this.Cable);
    this.AttachmentsUserControl.UpdateAttachmentDataListWithCable(this.Cable);
  }

  private void InitDialog(CUiFLEXCreationMode creationMode)
  {
    this.m_isWindowLoading = true;
    this.InitComboCreationMode(creationMode);
    this.InitUserControl();
    this.InitDialogMessage();
    this.AttributeViewModel.RadiusStepSize = CApCableUtility.ComputeRadiusStepSize();
    this.AttributeViewModel.LengthStepSize = CApCableUtility.ComputeLengthStepSize();
  }

  private void InitUserControl()
  {
    ICApCableFocusableControl focusEscapeControl = (ICApCableFocusableControl) new CApCableCompoundFocusableControl((IEnumerable<ICApCableFocusableControl>) new List<ICApCableFocusableControl>(2)
    {
      (ICApCableFocusableControl) new CApCableUIElementWrapper((UIElement) this.btnGenerate),
      (ICApCableFocusableControl) new CApCableUIElementWrapper((UIElement) this.btnClose)
    });
    this.InitBasicRequiredParametersControl(focusEscapeControl);
    this.InitBasicRequiredPointCloudParametersControl(focusEscapeControl);
    this.InitParametersUserControl();
    this.InitAttachmentUserControl();
    this.InitParametersPointCloudUserControl();
  }

  private void EndOfLoadingControl()
  {
    this.ParametersPointCloudUserControl.EndOfLoading();
    this.BasicRequiredParametersControl.EndOfLoading();
    this.BasicRequiredPointCloudParametersControl.EndOfLoading();
    this.ParametersUserControl.EndOfLoading();
    this.AttachmentsUserControl.EndOfLoading();
  }

  private void InitParametersPointCloudUserControl()
  {
    this.ParametersPointCloudUserControl.StartOfLoading();
    this.ParametersPointCloudUserControl.InitControl(this.AttributeViewModel);
  }

  private void InitBasicRequiredParametersControl(ICApCableFocusableControl focusEscapeControl)
  {
    this.BasicRequiredParametersControl.StartOfLoading();
    this.BasicRequiredParametersControl.InitControl(this, this.AttributeViewModel, focusEscapeControl);
  }

  private void InitBasicRequiredPointCloudParametersControl(
    ICApCableFocusableControl focusEscapeControl)
  {
    this.BasicRequiredPointCloudParametersControl.StartOfLoading();
    this.BasicRequiredPointCloudParametersControl.InitControl(this.AttributeViewModel, focusEscapeControl);
  }

  private void InitParametersUserControl()
  {
    this.ParametersUserControl.StartOfLoading();
    this.ParametersUserControl.InitControl(this.AttributeViewModel);
  }

  private void InitAttachmentUserControl()
  {
    this.AttachmentsUserControl.AttributeViewModel = (ICApFLEXCableAttributeViewModel) this.AttributeViewModel;
    this.AttachmentsUserControl.InitControl(this.m_frameAttachmentRetriever, this.ParameterController);
    this.RegisterUserControlEvent();
  }

  private void InitComboCreationMode(CUiFLEXCreationMode creationMode)
  {
    if (!this.IsEditMode && creationMode != CUiFLEXCreationMode.FROM_POINT_CLOUD)
      creationMode = this.ParameterController.CreationMode;
    this.AttributeViewModel.CreationMode = creationMode;
    ObservableCollection<CApCableCreationModeComboBoxItems> observableCollection = new ObservableCollection<CApCableCreationModeComboBoxItems>();
    observableCollection.Add(new CApCableCreationModeComboBoxItems(CApFLEXStringTable.CableCreationModeManual, CUiFLEXCreationMode.MANUAL));
    observableCollection.Add(new CApCableCreationModeComboBoxItems(CApFLEXStringTable.CableCreationModeFromPointCloud, CUiFLEXCreationMode.FROM_POINT_CLOUD));
    this.CableCreationModeCombo.ItemsSource = (IEnumerable) observableCollection;
    this.CableCreationModeCombo.SelectedIndex = (int) creationMode;
  }

  private void InitCableParameters()
  {
    if (this.IsEditMode)
      this.CableController.InitViewModelWithCable(this.Cable);
    else
      this.CableController.InitViewModel();
  }

  private void InitializeUpdaters()
  {
    this.m_disposableObjects.Add((IDisposable) new CApCableObjectAttributeObserver((ICApFLEXCableAttributeViewModel) this.AttributeViewModel, (ITxObjectRoot) TxApplication.ActiveDocument.PhysicalRoot, this.CableController, this.AttachmentsUserControl));
    this.m_disposableObjects.Add((IDisposable) new CApCableStatusBarMessageUpdater((ICApFLEXCableAttributeViewModel) this.AttributeViewModel, this.m_simulationPlayer, (ICApCableStatusMessageFactory) this.CableStatusMessageFactory));
    this.m_disposableObjects.Add((IDisposable) new CApCableGenerateButtonEnabler((ICApFLEXCableAttributeViewModel) this.AttributeViewModel, (ICApFlexCableController) this.CableController));
    this.m_disposableObjects.Add((IDisposable) new CApCableLengthUpdater((ICApFLEXCableAttributeViewModel) this.AttributeViewModel));
    this.m_disposableObjects.Add((IDisposable) new CApCableFrameRegistryUpdater((ICApFLEXCableAttributeViewModel) this.AttributeViewModel, (ICApCableFrameRegistry) this.AttributeViewModel.CableStatusAnalysis.CableFrameAttachmentRetriever));
  }

  private void CreateParameterController(CUiFLEXCreateCableCmd command)
  {
    this.ParameterController = new CApFlexParameterController(command);
    this.ParameterController.Load();
  }

  private void InitDialogMessage()
  {
    this.AttributeViewModel.CableStatusAnalysis = new CApCableStatusAnalysis((ICApFLEXCableAttributeViewModel) this.AttributeViewModel, this.m_frameAttachmentRetriever);
    this.CableStatusMessageFactory = new CApCableStatusMessageFactory(this.AttributeViewModel.CableStatusAnalysis);
  }

  private void InitCableScopeStatus(ITxCable cable, ITxComponent parentEquipment)
  {
    this.Cable = cable;
    if (parentEquipment != null)
      this.ParentEquipment = (ITxObject) parentEquipment;
    else
      this.ParentEquipment = CApCableUtility.GetParentEquipment((ITxObject) cable);
  }

  public bool ShouldDisplayCableEditorEmptyToolTip() => true;

  private void UpdateCreationModeCombo(CUiFLEXCreationMode creationMode)
  {
    this.IsComboLoading = true;
    foreach (object obj in (IEnumerable) this.CableCreationModeCombo.Items)
    {
      if (obj is CApCableCreationModeComboBoxItems modeComboBoxItems && modeComboBoxItems.CreationMode == creationMode)
      {
        this.CableCreationModeCombo.SelectedItem = (object) modeComboBoxItems;
        this.IsComboLoading = false;
        return;
      }
    }
    this.IsComboLoading = false;
  }

  private void UpdateModelFrames()
  {
    this.AttributeViewModel.StartFrame = this.Cable.StartFrame;
    this.AttributeViewModel.EndFrame = this.Cable.EndFrame;
  }

  private bool AreAttachmentsValid()
  {
    return this.AttributeViewModel.CableStatusAnalysis.AreAttachmentsLengthSmallerThanCableLength() && this.AttributeViewModel.CableStatusAnalysis.ArePercentageLengthBetweenAttachmentsValid(out CApFLEXAttachmentErrorMessage _);
  }

  private bool CreateCable()
  {
    bool cable = false;
    using (new CApCableGenerationSession((ICApFLEXCableAttributeViewModel) this.AttributeViewModel))
    {
      using (new CApCableCursorChangeSession(System.Windows.Forms.Cursors.WaitCursor))
      {
        this.Cable = this.CableController.CreateCable();
        TxApplication.RefreshDisplay();
        cable = this.Cable != null;
        if (cable)
          this.UpdateModelFrames();
      }
    }
    return cable;
  }

  private bool UpdateCable(out string errorMessage)
  {
    bool flag = true;
    errorMessage = string.Empty;
    using (new CApCableGenerationSession((ICApFLEXCableAttributeViewModel) this.AttributeViewModel))
    {
      using (new CApCableCursorChangeSession(System.Windows.Forms.Cursors.WaitCursor))
      {
        flag = this.CableController.UpdateCable(ref errorMessage);
        TxApplication.RefreshDisplay();
        if (flag)
          this.UpdateModelFrames();
      }
    }
    return flag;
  }

  private void CreateOrUpdateCable()
  {
    this.CableController.SaveAndUpdateParameterValues();
    bool flag = this.AreAttachmentsValid();
    if (!flag)
    {
      int num1 = (int) TxMessageBox.ShowModal(CApFLEXStringTable.CABLE_WITH_ATTACHMENTS_CREATION_FAIL, CApFLEXStringTable.CABLE_ERROR_DIALOG_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    bool sameRobot = this.AttributeViewModel.CableStatusAnalysis.AreStartEndFrameAttachedToSameRobot();
    if (!sameRobot)
    {
      int num2 = (int) TxMessageBox.ShowModal(CApFLEXStringTable.CABLE_FRAMES_ATTACHED_DISTINCT_ROBOTS, CApFLEXStringTable.CABLE_ERROR_DIALOG_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    if (!(flag & sameRobot))
      return;
    if (this.IsEditMode)
    {
      string errorMessage;
      if (this.UpdateCable(out errorMessage))
        return;
      int num3 = (int) TxMessageBox.ShowModal(errorMessage, CApFLEXStringTable.CABLE_ERROR_DIALOG_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    else
    {
      try
      {
        if (this.CreateCable())
          return;
        int num4 = (int) TxMessageBox.ShowModal(CApCableExceptionMessageProvider.ComputeDefaultGenerationErrorMessage(CApCableExceptionMessageProvider.CableAction.CREATION), CApFLEXStringTable.CABLE_ERROR_DIALOG_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Hand);
      }
      catch (TxException ex)
      {
        int num5 = (int) TxMessageBox.ShowModal(CApCableExceptionMessageProvider.ComputeCableExceptionErrorMessage(ex, CApCableExceptionMessageProvider.CableAction.CREATION), CApFLEXStringTable.CABLE_ERROR_DIALOG_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Hand);
      }
    }
  }

  private void RegisterActiveDocumentEvents()
  {
    TxApplication.ActiveDocument.Unloading += new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
  }

  private void UnregisterActiveDocumentEvents()
  {
    TxApplication.ActiveDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
  }

  private void RegisterUserControlEvent()
  {
    this.AttachmentsUserControl.AttachmentDialogOpened += new CApCableEventHandler(this.AttachmentDialog_OpenedHandler);
    this.AttachmentsUserControl.AttachmentDialogClosed += new CApCableEventHandler(this.AttachmentDialog_ClosedHandler);
  }

  private void UnregisterUserControlEvent()
  {
    this.AttachmentsUserControl.AttachmentDialogOpened -= new CApCableEventHandler(this.AttachmentDialog_OpenedHandler);
    this.AttachmentsUserControl.AttachmentDialogClosed -= new CApCableEventHandler(this.AttachmentDialog_ClosedHandler);
  }

  private void AttachmentDialog_OpenedHandler() => ((UIElement) this).IsEnabled = false;

  private void AttachmentDialog_ClosedHandler() => ((UIElement) this).IsEnabled = true;

  private void ActiveDocument_Unloading(object sender, TxDocument_UnloadingEventArgs args)
  {
    ((Window) this).Close();
  }

  private void m_keyup(object sender, System.Windows.Input.KeyEventArgs e)
  {
    if (e.Key != Key.Escape)
      return;
    ((Window) this).Close();
  }

  private void StatusBar_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    if (this.m_isWindowLoading || e.NewSize.Height == e.PreviousSize.Height)
      return;
    this.SetVerticalSizeToContent();
  }

  private void CableCreationModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    if (this.m_isWindowLoading)
      return;
    this.m_comboChanged = true;
    if (this.CableCreationModeCombo.SelectedItem != null)
      this.AttributeViewModel.CreationMode = (this.CableCreationModeCombo.SelectedItem as CApCableCreationModeComboBoxItems).CreationMode;
    else
      this.UpdateCreationModeCombo(this.AttributeViewModel.CreationMode);
    if (this.IsComboLoading)
      return;
    this.SetVerticalSizeToContent();
  }

  public void SetVerticalSizeToContent()
  {
    ((FrameworkElement) this).MinHeight = 0.0;
    ((FrameworkElement) this).MaxHeight = double.PositiveInfinity;
    ((Window) this).SizeToContent = SizeToContent.Height;
    ((UIElement) this).UpdateLayout();
    ((FrameworkElement) this).MaxHeight = ((FrameworkElement) this).MinHeight = ((FrameworkElement) this).ActualHeight;
  }

  private void Expander_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    if (this.m_isWindowLoading || e.NewSize.Height == e.PreviousSize.Height)
      return;
    this.SetVerticalSizeToContent();
  }

  private void BtnGenerate_Click(object sender, RoutedEventArgs e) => this.CreateOrUpdateCable();

  private void BtnClose_Click(object sender, RoutedEventArgs e) => ((Window) this).Close();

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    System.Windows.Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/flexibles/windows/cuiflexcableneweditorwindow.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  internal Delegate _CreateDelegate(Type delegateType, string handler)
  {
    return Delegate.CreateDelegate(delegateType, (object) this, handler);
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        this.dMainDialog = (CUiFLEXCableNewEditorWindow) target;
        ((FrameworkElement) this.dMainDialog).Loaded += new RoutedEventHandler(this.TxWindow_Loaded);
        ((Window) this.dMainDialog).Closing += new CancelEventHandler(this.TxWindow_Closed);
        break;
      case 2:
        this.CableCreationChoiceGrid = (Grid) target;
        break;
      case 3:
        this.labelCableCreationMode = (TextBlock) target;
        break;
      case 4:
        this.CableCreationModeCombo = (System.Windows.Controls.ComboBox) target;
        this.CableCreationModeCombo.SelectionChanged += new SelectionChangedEventHandler(this.CableCreationModeCombo_SelectionChanged);
        break;
      case 5:
        this.BasicRequiredParametersControl = (CApCableBasicRequiredParametersControl) target;
        break;
      case 6:
        this.BasicRequiredPointCloudParametersControl = (CApCableBasicRequiredPointCloudParametersControl) target;
        break;
      case 7:
        this.ExpanderParameters = (Expander) target;
        this.ExpanderParameters.SizeChanged += new SizeChangedEventHandler(this.Expander_SizeChanged);
        break;
      case 8:
        this.ParametersUserControl = (CApCableParametersNewUserControl) target;
        break;
      case 9:
        this.ParametersPointCloudUserControl = (CApCableParametersPointCloudUserControl) target;
        break;
      case 10:
        this.ExpanderAttachments = (Expander) target;
        this.ExpanderAttachments.SizeChanged += new SizeChangedEventHandler(this.Expander_SizeChanged);
        break;
      case 11:
        this.AttachmentsUserControl = (CApCableAttachmentsNewUserControl) target;
        break;
      case 12:
        this.btnGenerate = (System.Windows.Controls.Button) target;
        this.btnGenerate.Click += new RoutedEventHandler(this.BtnGenerate_Click);
        break;
      case 13:
        this.btnClose = (System.Windows.Controls.Button) target;
        this.btnClose.Click += new RoutedEventHandler(this.BtnClose_Click);
        break;
      case 14:
        ((FrameworkElement) target).SizeChanged += new SizeChangedEventHandler(this.StatusBar_SizeChanged);
        break;
      case 15:
        this.iMessageType = (Image) target;
        break;
      case 16 /*0x10*/:
        this.tbMessage = (TextBlock) target;
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }
}
